#!/usr/bin/env python3
"""
网络连接管理和错误处理模块

实现WiFi连接管理、断线重连、摄像头状态监控和流传输质量监控。
实现需求1.5, 2.5, 6.3：网络连接和错误处理。
"""

import logging
import asyncio
import threading
import time
import socket
import subprocess
import platform
from typing import Optional, Dict, Any, List, Callable, Tuple
from dataclasses import dataclass, field
from enum import Enum
from datetime import datetime, timedelta
import json
import psutil
import ping3

from .esp32_camera_driver import ESP32CameraDriver, CameraState
from .video_stream_server import VideoStreamManager, StreamConfig

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class NetworkState(Enum):
    """网络状态"""
    DISCONNECTED = "disconnected"
    CONNECTING = "connecting"
    CONNECTED = "connected"
    UNSTABLE = "unstable"
    ERROR = "error"


class ConnectionType(Enum):
    """连接类型"""
    WIFI = "wifi"
    ETHERNET = "ethernet"
    CELLULAR = "cellular"
    UNKNOWN = "unknown"


@dataclass
class NetworkInterface:
    """网络接口信息"""
    name: str
    type: ConnectionType
    ip_address: Optional[str] = None
    mac_address: Optional[str] = None
    is_active: bool = False
    signal_strength: Optional[int] = None  # WiFi信号强度 (dBm)
    speed: Optional[int] = None  # 连接速度 (Mbps)


@dataclass
class NetworkStats:
    """网络统计信息"""
    bytes_sent: int = 0
    bytes_received: int = 0
    packets_sent: int = 0
    packets_received: int = 0
    errors_in: int = 0
    errors_out: int = 0
    drops_in: int = 0
    drops_out: int = 0
    
    # 连接质量指标
    latency_ms: float = 0.0
    packet_loss_rate: float = 0.0
    bandwidth_mbps: float = 0.0
    jitter_ms: float = 0.0
    
    # 历史数据
    connection_uptime: timedelta = timedelta()
    reconnection_count: int = 0
    last_disconnection: Optional[datetime] = None


@dataclass
class WiFiConfig:
    """WiFi配置"""
    ssid: str
    password: str
    security: str = "WPA2"  # WPA2, WPA3, WEP, OPEN
    hidden: bool = False
    auto_connect: bool = True
    priority: int = 0  # 连接优先级


@dataclass
class ConnectionConfig:
    """连接配置"""
    # WiFi配置
    wifi_configs: List[WiFiConfig] = field(default_factory=list)
    wifi_scan_interval: float = 30.0
    wifi_connect_timeout: float = 30.0
    
    # 重连配置
    auto_reconnect: bool = True
    reconnect_interval: float = 5.0
    max_reconnect_attempts: int = 10
    exponential_backoff: bool = True
    max_backoff_interval: float = 300.0
    
    # 监控配置
    ping_interval: float = 10.0
    ping_timeout: float = 5.0
    ping_targets: List[str] = field(default_factory=lambda: ["8.8.8.8", "1.1.1.1"])
    quality_check_interval: float = 60.0
    
    # 故障检测配置
    connection_timeout: float = 30.0
    stability_threshold: float = 0.8  # 连接稳定性阈值
    quality_threshold: float = 0.7    # 连接质量阈值


class NetworkMonitor:
    """网络监控器"""
    
    def __init__(self, config: ConnectionConfig):
        self.config = config
        self.state = NetworkState.DISCONNECTED
        self.current_interface: Optional[NetworkInterface] = None
        self.stats = NetworkStats()
        self.interfaces: Dict[str, NetworkInterface] = {}
        
        # 监控线程
        self.monitor_thread: Optional[threading.Thread] = None
        self.running = False
        self._stop_event = threading.Event()
        
        # 回调函数
        self.state_callback: Optional[Callable[[NetworkState], None]] = None
        self.quality_callback: Optional[Callable[[float], None]] = None
        self.error_callback: Optional[Callable[[Exception], None]] = None
        
        # 内部状态
        self._last_stats_time = time.time()
        self._connection_start_time: Optional[float] = None
        self._ping_history: List[Tuple[float, float]] = []  # (timestamp, latency)
        
    def set_state_callback(self, callback: Callable[[NetworkState], None]):
        """设置状态回调函数"""
        self.state_callback = callback
        
    def set_quality_callback(self, callback: Callable[[float], None]):
        """设置质量回调函数"""
        self.quality_callback = callback
        
    def set_error_callback(self, callback: Callable[[Exception], None]):
        """设置错误回调函数"""
        self.error_callback = callback
    
    def _set_state(self, new_state: NetworkState):
        """设置网络状态"""
        if self.state != new_state:
            old_state = self.state
            self.state = new_state
            logger.info(f"网络状态变更: {old_state.value} -> {new_state.value}")
            
            if new_state == NetworkState.CONNECTED and old_state != NetworkState.CONNECTED:
                self._connection_start_time = time.time()
            elif new_state == NetworkState.DISCONNECTED and old_state == NetworkState.CONNECTED:
                self.stats.last_disconnection = datetime.now()
                if self._connection_start_time:
                    uptime = time.time() - self._connection_start_time
                    self.stats.connection_uptime += timedelta(seconds=uptime)
            
            if self.state_callback:
                try:
                    self.state_callback(new_state)
                except Exception as e:
                    logger.error(f"状态回调函数执行失败: {e}")
    
    def _handle_error(self, error: Exception):
        """处理错误"""
        logger.error(f"网络错误: {error}")
        
        if self.error_callback:
            try:
                self.error_callback(error)
            except Exception as e:
                logger.error(f"错误回调函数执行失败: {e}")
    
    def start_monitoring(self) -> bool:
        """开始网络监控"""
        try:
            if self.running:
                logger.warning("网络监控已在运行")
                return True
            
            self.running = True
            self._stop_event.clear()
            
            self.monitor_thread = threading.Thread(
                target=self._monitor_loop,
                name="NetworkMonitor",
                daemon=True
            )
            self.monitor_thread.start()
            
            logger.info("网络监控已启动")
            return True
            
        except Exception as e:
            self._handle_error(e)
            return False
    
    def stop_monitoring(self):
        """停止网络监控"""
        if not self.running:
            return
        
        logger.info("停止网络监控...")
        self.running = False
        self._stop_event.set()
        
        if self.monitor_thread and self.monitor_thread.is_alive():
            self.monitor_thread.join(timeout=5.0)
            if self.monitor_thread.is_alive():
                logger.warning("监控线程未能正常停止")
        
        logger.info("网络监控已停止")
    
    def _monitor_loop(self):
        """监控主循环"""
        logger.info("网络监控循环开始")
        
        while self.running and not self._stop_event.is_set():
            try:
                # 更新网络接口信息
                self._update_interfaces()
                
                # 检查连接状态
                self._check_connection_status()
                
                # 测试连接质量
                self._test_connection_quality()
                
                # 更新统计信息
                self._update_stats()
                
                # 等待下一次检查
                self._stop_event.wait(self.config.ping_interval)
                
            except Exception as e:
                self._handle_error(e)
                self._stop_event.wait(1.0)  # 错误后短暂等待
        
        logger.info("网络监控循环结束")
    
    def _update_interfaces(self):
        """更新网络接口信息"""
        try:
            # 获取网络接口统计信息
            net_io = psutil.net_io_counters(pernic=True)
            addrs = psutil.net_if_addrs()
            
            for interface_name, io_stats in net_io.items():
                if interface_name not in self.interfaces:
                    # 确定接口类型
                    if 'wlan' in interface_name.lower() or 'wifi' in interface_name.lower():
                        interface_type = ConnectionType.WIFI
                    elif 'eth' in interface_name.lower() or 'en' in interface_name.lower():
                        interface_type = ConnectionType.ETHERNET
                    else:
                        interface_type = ConnectionType.UNKNOWN
                    
                    self.interfaces[interface_name] = NetworkInterface(
                        name=interface_name,
                        type=interface_type
                    )
                
                interface = self.interfaces[interface_name]
                
                # 更新IP地址和MAC地址
                if interface_name in addrs:
                    for addr in addrs[interface_name]:
                        if addr.family == socket.AF_INET:
                            interface.ip_address = addr.address
                        elif addr.family == psutil.AF_LINK:
                            interface.mac_address = addr.address
                
                # 检查接口是否活跃
                interface.is_active = io_stats.bytes_sent > 0 or io_stats.bytes_recv > 0
                
                # 如果是当前活跃的接口，更新为当前接口
                if interface.is_active and interface.ip_address and not interface.ip_address.startswith('127.'):
                    self.current_interface = interface
        
        except Exception as e:
            logger.error(f"更新网络接口信息失败: {e}")
    
    def _check_connection_status(self):
        """检查连接状态"""
        try:
            if not self.current_interface or not self.current_interface.ip_address:
                self._set_state(NetworkState.DISCONNECTED)
                return
            
            # 检查是否能访问外网
            can_reach_internet = False
            for target in self.config.ping_targets:
                if self._ping_host(target):
                    can_reach_internet = True
                    break
            
            if can_reach_internet:
                # 检查连接稳定性
                stability = self._calculate_connection_stability()
                if stability >= self.config.stability_threshold:
                    self._set_state(NetworkState.CONNECTED)
                else:
                    self._set_state(NetworkState.UNSTABLE)
            else:
                self._set_state(NetworkState.DISCONNECTED)
        
        except Exception as e:
            logger.error(f"检查连接状态失败: {e}")
            self._set_state(NetworkState.ERROR)
    
    def _test_connection_quality(self):
        """测试连接质量"""
        try:
            if self.state not in [NetworkState.CONNECTED, NetworkState.UNSTABLE]:
                return
            
            # 测试延迟
            latencies = []
            for target in self.config.ping_targets:
                latency = self._ping_host(target, return_latency=True)
                if latency is not None:
                    latencies.append(latency)
            
            if latencies:
                avg_latency = sum(latencies) / len(latencies)
                self.stats.latency_ms = avg_latency
                
                # 记录延迟历史
                current_time = time.time()
                self._ping_history.append((current_time, avg_latency))
                
                # 保持历史记录在合理范围内
                cutoff_time = current_time - 300  # 保留5分钟历史
                self._ping_history = [(t, l) for t, l in self._ping_history if t > cutoff_time]
                
                # 计算抖动
                if len(self._ping_history) > 1:
                    latency_values = [l for _, l in self._ping_history]
                    avg = sum(latency_values) / len(latency_values)
                    variance = sum((l - avg) ** 2 for l in latency_values) / len(latency_values)
                    self.stats.jitter_ms = variance ** 0.5
                
                # 计算连接质量分数
                quality_score = self._calculate_quality_score(avg_latency, self.stats.jitter_ms)
                
                if self.quality_callback:
                    self.quality_callback(quality_score)
        
        except Exception as e:
            logger.error(f"测试连接质量失败: {e}")
    
    def _ping_host(self, host: str, return_latency: bool = False) -> Optional[float]:
        """Ping主机"""
        try:
            latency = ping3.ping(host, timeout=self.config.ping_timeout)
            if latency is not None:
                if return_latency:
                    return latency * 1000  # 转换为毫秒
                else:
                    return True
            return None if return_latency else False
        except Exception as e:
            logger.debug(f"Ping {host} 失败: {e}")
            return None if return_latency else False
    
    def _calculate_connection_stability(self) -> float:
        """计算连接稳定性"""
        if len(self._ping_history) < 5:
            return 1.0  # 数据不足，假设稳定
        
        # 计算最近的ping成功率
        recent_pings = self._ping_history[-10:]  # 最近10次ping
        success_count = sum(1 for _, latency in recent_pings if latency > 0)
        
        return success_count / len(recent_pings)
    
    def _calculate_quality_score(self, latency: float, jitter: float) -> float:
        """计算连接质量分数 (0-1)"""
        # 基于延迟的分数 (延迟越低分数越高)
        latency_score = max(0, 1 - latency / 1000)  # 1秒延迟为0分
        
        # 基于抖动的分数 (抖动越低分数越高)
        jitter_score = max(0, 1 - jitter / 100)  # 100ms抖动为0分
        
        # 综合分数
        return (latency_score * 0.7 + jitter_score * 0.3)
    
    def _update_stats(self):
        """更新统计信息"""
        try:
            current_time = time.time()
            
            if self.current_interface:
                # 获取网络IO统计
                net_io = psutil.net_io_counters(pernic=True)
                if self.current_interface.name in net_io:
                    io_stats = net_io[self.current_interface.name]
                    
                    # 计算带宽
                    time_delta = current_time - self._last_stats_time
                    if time_delta > 0:
                        bytes_delta = (io_stats.bytes_sent + io_stats.bytes_recv) - (self.stats.bytes_sent + self.stats.bytes_received)
                        self.stats.bandwidth_mbps = (bytes_delta * 8) / (time_delta * 1024 * 1024)  # Mbps
                    
                    # 更新统计信息
                    self.stats.bytes_sent = io_stats.bytes_sent
                    self.stats.bytes_received = io_stats.bytes_recv
                    self.stats.packets_sent = io_stats.packets_sent
                    self.stats.packets_received = io_stats.packets_recv
                    self.stats.errors_in = io_stats.errin
                    self.stats.errors_out = io_stats.errout
                    self.stats.drops_in = io_stats.dropin
                    self.stats.drops_out = io_stats.dropout
            
            self._last_stats_time = current_time
            
        except Exception as e:
            logger.error(f"更新统计信息失败: {e}")
    
    def get_status(self) -> Dict[str, Any]:
        """获取网络状态"""
        return {
            'state': self.state.value,
            'current_interface': {
                'name': self.current_interface.name,
                'type': self.current_interface.type.value,
                'ip_address': self.current_interface.ip_address,
                'mac_address': self.current_interface.mac_address,
                'is_active': self.current_interface.is_active
            } if self.current_interface else None,
            'stats': {
                'latency_ms': round(self.stats.latency_ms, 2),
                'jitter_ms': round(self.stats.jitter_ms, 2),
                'bandwidth_mbps': round(self.stats.bandwidth_mbps, 2),
                'packet_loss_rate': round(self.stats.packet_loss_rate, 4),
                'bytes_sent': self.stats.bytes_sent,
                'bytes_received': self.stats.bytes_received,
                'connection_uptime': self.stats.connection_uptime.total_seconds(),
                'reconnection_count': self.stats.reconnection_count
            },
            'interfaces': {
                name: {
                    'type': interface.type.value,
                    'ip_address': interface.ip_address,
                    'is_active': interface.is_active
                }
                for name, interface in self.interfaces.items()
            }
        }


class WiFiManager:
    """WiFi连接管理器"""
    
    def __init__(self, config: ConnectionConfig):
        self.config = config
        self.current_config: Optional[WiFiConfig] = None
        self.available_networks: List[Dict[str, Any]] = []
        self.connection_attempts = 0
        self.last_scan_time = 0
        
    def scan_networks(self) -> List[Dict[str, Any]]:
        """扫描可用的WiFi网络"""
        try:
            current_time = time.time()
            if current_time - self.last_scan_time < self.config.wifi_scan_interval:
                return self.available_networks
            
            # 在实际ESP32实现中，这里会调用WiFi扫描API
            # 这里模拟扫描结果
            self.available_networks = [
                {
                    'ssid': 'TestNetwork1',
                    'signal_strength': -45,
                    'security': 'WPA2',
                    'channel': 6
                },
                {
                    'ssid': 'TestNetwork2',
                    'signal_strength': -60,
                    'security': 'WPA3',
                    'channel': 11
                }
            ]
            
            self.last_scan_time = current_time
            logger.info(f"扫描到 {len(self.available_networks)} 个WiFi网络")
            
            return self.available_networks
            
        except Exception as e:
            logger.error(f"WiFi网络扫描失败: {e}")
            return []
    
    def connect_to_network(self, wifi_config: WiFiConfig) -> bool:
        """连接到WiFi网络"""
        try:
            logger.info(f"尝试连接到WiFi网络: {wifi_config.ssid}")
            
            # 在实际ESP32实现中，这里会调用WiFi连接API
            # 这里模拟连接过程
            time.sleep(2)  # 模拟连接延迟
            
            # 模拟90%的连接成功率
            import random
            if random.random() > 0.1:
                self.current_config = wifi_config
                logger.info(f"成功连接到WiFi网络: {wifi_config.ssid}")
                return True
            else:
                logger.error(f"连接到WiFi网络失败: {wifi_config.ssid}")
                return False
                
        except Exception as e:
            logger.error(f"WiFi连接过程中发生错误: {e}")
            return False
    
    def disconnect(self):
        """断开WiFi连接"""
        try:
            if self.current_config:
                logger.info(f"断开WiFi连接: {self.current_config.ssid}")
                self.current_config = None
            
            # 在实际ESP32实现中，这里会调用WiFi断开API
            
        except Exception as e:
            logger.error(f"WiFi断开过程中发生错误: {e}")
    
    def get_connection_info(self) -> Optional[Dict[str, Any]]:
        """获取当前连接信息"""
        if not self.current_config:
            return None
        
        return {
            'ssid': self.current_config.ssid,
            'security': self.current_config.security,
            'signal_strength': -50,  # 模拟信号强度
            'ip_address': '192.168.1.100',  # 模拟IP地址
            'connected_time': datetime.now().isoformat()
        }


class ConnectionManager:
    """连接管理器"""
    
    def __init__(self, config: ConnectionConfig):
        self.config = config
        self.network_monitor = NetworkMonitor(config)
        self.wifi_manager = WiFiManager(config)
        self.camera_driver: Optional[ESP32CameraDriver] = None
        self.stream_manager: Optional[VideoStreamManager] = None
        
        # 重连状态
        self.reconnect_thread: Optional[threading.Thread] = None
        self.reconnecting = False
        self.reconnect_attempts = 0
        self.last_reconnect_time = 0
        
        # 设置回调
        self.network_monitor.set_state_callback(self._on_network_state_changed)
        self.network_monitor.set_error_callback(self._on_network_error)
    
    def set_camera_driver(self, driver: ESP32CameraDriver):
        """设置摄像头驱动"""
        self.camera_driver = driver
    
    def set_stream_manager(self, manager: VideoStreamManager):
        """设置流管理器"""
        self.stream_manager = manager
    
    def start(self) -> bool:
        """启动连接管理"""
        try:
            # 启动网络监控
            if not self.network_monitor.start_monitoring():
                logger.error("启动网络监控失败")
                return False
            
            # 尝试连接WiFi
            if self.config.wifi_configs:
                self._attempt_wifi_connection()
            
            logger.info("连接管理器启动成功")
            return True
            
        except Exception as e:
            logger.error(f"启动连接管理器失败: {e}")
            return False
    
    def stop(self):
        """停止连接管理"""
        logger.info("停止连接管理器...")
        
        # 停止重连线程
        self.reconnecting = False
        if self.reconnect_thread and self.reconnect_thread.is_alive():
            self.reconnect_thread.join(timeout=5.0)
        
        # 停止网络监控
        self.network_monitor.stop_monitoring()
        
        # 断开WiFi连接
        self.wifi_manager.disconnect()
        
        logger.info("连接管理器已停止")
    
    def _attempt_wifi_connection(self) -> bool:
        """尝试WiFi连接"""
        # 扫描可用网络
        available_networks = self.wifi_manager.scan_networks()
        available_ssids = {net['ssid'] for net in available_networks}
        
        # 按优先级排序配置的网络
        sorted_configs = sorted(self.config.wifi_configs, key=lambda x: x.priority, reverse=True)
        
        for wifi_config in sorted_configs:
            if wifi_config.ssid in available_ssids:
                if self.wifi_manager.connect_to_network(wifi_config):
                    return True
        
        logger.warning("无法连接到任何配置的WiFi网络")
        return False
    
    def _on_network_state_changed(self, state: NetworkState):
        """网络状态变更回调"""
        logger.info(f"网络状态变更: {state.value}")
        
        if state == NetworkState.DISCONNECTED and self.config.auto_reconnect:
            self._start_reconnection()
        elif state == NetworkState.CONNECTED:
            self.reconnect_attempts = 0
            self.reconnecting = False
    
    def _on_network_error(self, error: Exception):
        """网络错误回调"""
        logger.error(f"网络错误: {error}")
        
        # 检查摄像头状态
        if self.camera_driver and self.camera_driver.state == CameraState.ERROR:
            logger.warning("检测到摄像头错误，尝试重新初始化")
            self._recover_camera()
    
    def _start_reconnection(self):
        """开始重连过程"""
        if self.reconnecting or self.reconnect_attempts >= self.config.max_reconnect_attempts:
            return
        
        current_time = time.time()
        
        # 计算重连间隔
        if self.config.exponential_backoff:
            interval = min(
                self.config.reconnect_interval * (2 ** self.reconnect_attempts),
                self.config.max_backoff_interval
            )
        else:
            interval = self.config.reconnect_interval
        
        if current_time - self.last_reconnect_time < interval:
            return
        
        self.reconnecting = True
        self.reconnect_thread = threading.Thread(
            target=self._reconnection_loop,
            name="ConnectionReconnect",
            daemon=True
        )
        self.reconnect_thread.start()
    
    def _reconnection_loop(self):
        """重连循环"""
        logger.info("开始网络重连...")
        
        while self.reconnecting and self.reconnect_attempts < self.config.max_reconnect_attempts:
            try:
                self.reconnect_attempts += 1
                self.last_reconnect_time = time.time()
                
                logger.info(f"重连尝试 {self.reconnect_attempts}/{self.config.max_reconnect_attempts}")
                
                # 断开当前连接
                self.wifi_manager.disconnect()
                time.sleep(2)
                
                # 尝试重新连接
                if self._attempt_wifi_connection():
                    logger.info("网络重连成功")
                    self.reconnecting = False
                    return
                
                # 计算下次重连间隔
                if self.config.exponential_backoff:
                    interval = min(
                        self.config.reconnect_interval * (2 ** self.reconnect_attempts),
                        self.config.max_backoff_interval
                    )
                else:
                    interval = self.config.reconnect_interval
                
                logger.info(f"重连失败，{interval}秒后重试")
                time.sleep(interval)
                
            except Exception as e:
                logger.error(f"重连过程中发生错误: {e}")
                time.sleep(self.config.reconnect_interval)
        
        if self.reconnect_attempts >= self.config.max_reconnect_attempts:
            logger.error("达到最大重连次数，停止重连")
        
        self.reconnecting = False
    
    def _recover_camera(self):
        """恢复摄像头"""
        if not self.camera_driver:
            return
        
        try:
            logger.info("尝试恢复摄像头...")
            
            # 停止当前捕获
            if self.camera_driver.state == CameraState.STREAMING:
                self.camera_driver.stop_capture()
            
            # 重新初始化
            if self.camera_driver.initialize():
                # 重新开始捕获
                if self.camera_driver.start_capture():
                    logger.info("摄像头恢复成功")
                else:
                    logger.error("摄像头恢复失败：无法开始捕获")
            else:
                logger.error("摄像头恢复失败：初始化失败")
                
        except Exception as e:
            logger.error(f"摄像头恢复过程中发生错误: {e}")
    
    def get_status(self) -> Dict[str, Any]:
        """获取连接管理器状态"""
        return {
            'network': self.network_monitor.get_status(),
            'wifi': self.wifi_manager.get_connection_info(),
            'reconnection': {
                'active': self.reconnecting,
                'attempts': self.reconnect_attempts,
                'max_attempts': self.config.max_reconnect_attempts
            },
            'camera_status': self.camera_driver.get_status() if self.camera_driver else None,
            'stream_status': self.stream_manager.get_all_status() if self.stream_manager else None
        }
    
    def force_reconnect(self):
        """强制重连"""
        logger.info("强制重连网络...")
        self.reconnect_attempts = 0
        self._start_reconnection()
    
    def add_wifi_config(self, wifi_config: WiFiConfig):
        """添加WiFi配置"""
        self.config.wifi_configs.append(wifi_config)
        logger.info(f"添加WiFi配置: {wifi_config.ssid}")
    
    def remove_wifi_config(self, ssid: str):
        """移除WiFi配置"""
        self.config.wifi_configs = [
            config for config in self.config.wifi_configs
            if config.ssid != ssid
        ]
        logger.info(f"移除WiFi配置: {ssid}")


def main():
    """测试函数"""
    # 创建连接配置
    config = ConnectionConfig(
        wifi_configs=[
            WiFiConfig(ssid="TestNetwork1", password="password123", priority=1),
            WiFiConfig(ssid="TestNetwork2", password="password456", priority=2)
        ],
        auto_reconnect=True,
        reconnect_interval=5.0,
        max_reconnect_attempts=5
    )
    
    # 创建连接管理器
    connection_manager = ConnectionManager(config)
    
    try:
        # 启动连接管理
        if connection_manager.start():
            print("连接管理器启动成功")
            
            # 运行一段时间
            time.sleep(30)
            
            # 显示状态
            status = connection_manager.get_status()
            print(f"连接状态: {json.dumps(status, indent=2, ensure_ascii=False)}")
            
        else:
            print("连接管理器启动失败")
    
    finally:
        connection_manager.stop()


if __name__ == "__main__":
    main()